package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConst;
import com.itheima.common.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Reference
    ValidateCodeService validateCodeService;

    @Reference
    OrderService orderService;

    @RequestMapping("/findById")
    public Result findById(Integer id){
        Map map = orderService.findById(id);

        //因为传给前端的只能是字符串形式 如果传给他日期的话 他会计算成毫秒值显示出来
        //所以直接把查好的数据里的日期拿出来 把他转为我们想要的格式的字符串 然后再塞进去
        //这样前端就可以显示这个字符串形式的日期了
        Object orderDate = map.get("orderDate");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(orderDate);
        map.put("orderDate",format);

        return new Result(true, MessageConst.ORDER_SUCCESS,map);
    }


    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String,String> map) throws ParseException {
        log.debug("付1--获得了前端传过来的数据 用map来接收 ： "+map);
        String validateCode =map.get("validateCode");
        String telephone = map.get("telephone");

        boolean b = validateCodeService.checkValidateCode(telephone, RedisMessageConstant.SENDTYPE_ORDER, validateCode);
        if (!b){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }

        Result result = orderService.addOrderData(map);

        if (result.isFlag()){
            validateCodeService.sendCommonShortMessage(telephone,"您已预约成功!");
        }

        return result;
    }

}
